package com.tl.boot.common.vo;

import com.alibaba.fastjson.JSON;
import com.tl.boot.common.enums.ResultEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;

/**
 * com.tl.boot.common.vo -- ResponseVO
 * Description:
 * Created by joshua_liu <a href="mailto:joshualwork@163.com"></a>
 * On 2019/9/10 11:59
 */
@ApiModel("通用响应对象")
public class ResponseVO<T> {

    @ApiModelProperty(value = "响应结果编码", dataType = "String")
    private String code;

    @ApiModelProperty(value = "响应信息", dataType = "String")
    private String message;

    @ApiModelProperty(value = "响应泛型对象")
    private T data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    /**
     * 响应成功
     */
    public static ResponseVO buildSuccess() {
        ResponseVO result = new ResponseVO<String>();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMessage(ResultEnum.SUCCESS.getMessage());
        return result;
    }

    /**
     * 响应成功
     */
    public static <T> ResponseVO<T> buildSuccess(T object) {
        ResponseVO result = new ResponseVO<T>();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMessage(ResultEnum.SUCCESS.getMessage());

        if (null != object) {
            result.setData(object);
        }

        return result;
    }

    /**
     * 响应成功
     */
    public static <T> ResponseVO<PageInfoVO<T>> buildSuccess(List<T> list, Long total) {
        ResponseVO result = new ResponseVO<T>();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMessage(ResultEnum.SUCCESS.getMessage());
        if (null != list) {
            PageInfoVO<T> pageInfoVO = new PageInfoVO(total,list);
            result.setData(pageInfoVO);
        }
        return result;
    }

    /**
     * 响应失败
     *
     * @param codeEnum 错误枚举
     */
    public static ResponseVO buildFail(ResultEnum codeEnum) {
        ResponseVO result = new ResponseVO<String>();
        result.setCode(codeEnum.getCode());
        result.setMessage(codeEnum.getMessage());
        return result;
    }

    /**
     * 响应失败
     *
     * @param codeEnum 错误枚举
     */
    public static ResponseVO buildFail(ResultEnum codeEnum, String... args) {
        ResponseVO result = new ResponseVO<String>();
        result.setCode(codeEnum.getCode());
        result.setMessage(String.format(codeEnum.getMessage(), args));
        return result;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}


